<?php
/**
* Sections
* Manage all sections in the system
* 
* @package Section
* @author Argem Gerald R. Flores <argemgrflores@gmail.com>
* @version 1.0
*/
class Section {
	/**
	* @var mixed Mysql connection
	*/
	var $mysqli = null;
	/**
	* @var array User credentials (id, email, type)
	*/
	var $user = null;
	/**
	* @var array Notifications
	*/
	var $notif = array();
	/**
	* @var string Area of concentration
	*/
	var $area = 'proj';
	
	/**
	* Section constructor
	* Initializes section variables for intended request
	* 
	* @param string $area Area of concentration
	* @param resource $mysqli Current mysql connection
	* @param resource $user User credentials (id, email, type)
	*/
	function __construct($area, $mysqli, $user) {
		require_once "class/setting.php";
		require_once "class/file.php";
		require_once "class/resource.php";
		require_once "class/location.php";
		require_once "class/microorganism.php";
		require_once "class/image.php";
		require_once "class/document.php";
		require_once "class/project.php";
		require_once "class/tool.php";
		
		$this->mysqli = $mysqli;
		$this->user = $user;
		$this->area = $area;
		
		switch($area) {
			case 'proj':
				$this->sectb = 'ProjSections';
				$this->imgtb = 'ProjImgs';
				$this->doctb = 'ProjDocs';
				$this->imgsectb = 'ProjSecImgs';
				$this->docsectb = 'ProjSecDocs';
			break;
		}
	} # __construct
	
	/**
	* Create section
	* Create a new section
	* 
	* @access public
	* @param string $id Area ID
	* @param mixed $secs Section details
	* @param mixed $files Files of each section
	* @param string $categ Category
	* @param string $visib Visibility
	* 
	* @return boolean true on success, false on failure
	*/
	public function create($id, $secs, $files, $categ, $visib) {
		# Append sections
		if(!empty($secs["val"])) {
			$this->append($id, $secs, $files, $categ, $visib);
		}
		
		# Notifications
		if(!empty($this->notif)) {
			//echo '<pre>', var_dump($this->notif), '</pre>';
			return false;
		}
		
		return true;
	} # function create
	
	/**
	* Update sections
	* Update an existing section on the system
	* 
	* @access public
	* @param string $id Area ID
	* @param mixed $secs Sections to be edited
	* @param mixed $files Files of each section
	* @param mixed $asecs Additional sections
	* @param mixed $afiles Files of each additional section
	* @param mixed $rsecs Sections to be removed
	* @param mixed $rimgs Images to be removed
	* @param mixed $rdocs Documents to be removed
	* @param string $categ Category
	* @param string $visib Visibility
	* 
	* @return array Notifications
	*/
	public function update($id, $secs, $files, $asecs, $afiles, $rsecs, $rimgs, $rdocs, $categ, $visib) {
		# Update sections
		if(!empty($secs["val"])) {
			$this->modify($id, $secs);
		}
		
		# Modify files in sections
		if(!empty($files["name"])) {
			$this->modifyFile($id, $secs, $files, $categ, $visib);
		}
		
		# Remove images/documents
		if(!empty($rimgs) or !empty($rdocs)) {
			$this->removeFile($id, $secs, $rimgs, $rdocs);
		}
		
		# Append new sections
		if(!empty($asecs["val"])) {
			$this->append($id, $asecs, $afiles, $categ, $visib);
		}
		
		# Remove sections
		if(!empty($rsecs)) {
			$this->remove($rsecs, $id);
		}
		
		# Notifications
		if(!empty($this->notif)) {
			return $this->notif;
		}
		
		return true;
	} # function update
	
	/**
	* Append sections
	* Append sections associated to that area
	* 
	* @access public
	* @param string $id ID of area
	* @param array $addl Sections to be appended
	* @param mixed $addl Files of each additional section
	* @param string $categ Category
	* @param string $visib Visibility
	*/
	public function append($id, $secs, $files, $categ, $visib) {
		# Iterate through each section
		foreach($secs["val"] as $i => $sec) {
			# Empty section header, skip
			if(empty($sec['head'])) continue;
			
			# Section ID
			$secid = Tool::generateID('sec');
			
			# Create new section
			$ins = "
				INSERT INTO {$this->sectb} VALUES (
					'{$id}', '{$secid}', '".mysql_real_escape_string(Tool::trimout($sec['head']))."',
					".(empty($sec['cont']) ? 'NULL' : "'".mysql_real_escape_string(Tool::trimout($sec['cont']))."'").",
					'{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."'
				)
			";
			
			# Error in creating section
			if(!$this->mysqli->query($ins)) {
				$this->notif[] = "ERROR: ins sec <br/>";
			}
			
			# Append new files
			if(!empty($files["name"][$i])) {
				$this->appendFile($id, $i, $secid, $files, $categ, $visib);
			}
		}
	} # function append
	
	/**
	* Modify sections
	* Modify section details associated to that area
	* 
	* @access public
	* @param string $id ID of area
	* @param array $secs Section details to be edited
	*/
	public function modify($id, $secs) {
		# Iterate through each section
		foreach($secs["val"] as $i => $sec) {
			$values = '';
			
			# Update header
			if(isset($sec["head"])) {
				$values .= "Header='{$sec["head"]}'";
			}
			
			# Update contents
			if(isset($sec["cont"])) {
				if(!empty($values)) {
					$values .= ", ";
				}
				
				$values .= "Content='{$sec["cont"]}'";
			}
			
			# Update string
			$upd = "UPDATE {$this->sectb} SET {$values} WHERE CID='{$secs["id"][$i]}'";
			
			# Do mysql update
			if(!$this->mysqli->query($upd)) {
				$this->notif[] = "ERROR: upd sec";
			}
		}
	} # function modify
	
	/**
	* Append section files
	* Upload and append files to sections
	* 
	* @access public
	* @param string $id ID of area
	* @param integer $s Index of section
	* @param string $secID Section ID
	* @param mixed $files Files in each section
	* @param string $s Category
	* @param string $s Visibility
	*/
	public function appendFile($id, $s, $secID, $files, $categ, $visib) {
		# Iterate through each file
		foreach($files['name'][$s] as $i => $name) {
			# Decide on which type is to be uploaded
			switch($files['type'][$s][$i]) {
				# Images
				case 'image/jpeg':
				case 'image/gif':
					# Instantiate new Image
					$img = new Image('sec', array('pid'=>$id, 'sid'=>$secID, 'sec'=>$this->area), $this->mysqli, $this->user);
					
					# Create image
					$imgID = $img->create(
						array (
							'name'=>$name, 'type'=>$files['type'][$s][$i], 'size'=>$files['size'][$s][$i],
							'tmp_name'=>$files['tmp_name'][$s][$i], 'error'=>0
						), null, null, null, null, null, array('id'=>array($id)), null, null, $categ, $visib
					);
					
					# Created successfully
					if($imgID!==false) {
						# Append image to section
						$ins = "INSERT INTO {$this->imgsectb} VALUES ('{$id}', '{$secID}', '{$imgID}', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."')";
						
						if(!$this->mysqli->query($ins)) {
							$this->notif[] = "ERROR ins sec img<br/>";
						}
					}
				break;
				
				# Documents
				case "application/pdf":
					# Instantiate new document
					$doc = new Document('sec', array('pid'=>$id, 'sid'=>$secID, 'sec'=>$this->area), $this->mysqli, $this->user);
					
					# Create new document
					$docID = $doc->create(
						array (
							'name'=>$name, 'type'=>$files['type'][$s][$i], 'size'=>$files['size'][$s][$i],
							'tmp_name'=>$files['tmp_name'][$s][$i], 'error'=>0
						), null, null, null, null, null, array('id'=>array($id)), null, null, $categ, $visib
					);
					
					# Created successfully
					if($docID!==false) {
						# Append document to section
						$ins = "INSERT INTO {$this->docsectb} VALUES ('{$id}', '{$secID}', '{$docID}', '{$this->user['id']}', '".date('Y-m-d H:i:s:ms')."')";
						
						if(!$this->mysqli->query($ins)) {
							$this->notif[] = "ERROR: ftp put doc 1";
						}
					}
				break;
			}
		}
	} # function appendFile
	
	/**
	* Modify section files
	* Append or remove section files
	* 
	* @access public
	* @param string $id ID of area
	* @param mixed $secs Sections
	* @param mixed $files Files in each section
	* @param string $s Category
	* @param string $s Visibility
	*/
	public function modifyFile($id, $secs, $files, $categ, $visib) {
		# Modify files in sections
		foreach($secs["id"] as $i => $secID) {
			if(!empty($files["name"][$i])) {
				$this->appendFile($id, $i, $secID, $files, $categ, $visib);
			}
		}
	} # function modifyFile
	
	/**
	* Remove sections
	* Remove sections associated to that area
	* 
	* @access public
	* @param array $rsecs Sections to be removed
	* @param string $id ID of area
	*/
	public function remove($rsecs, $id) {
		# Remove section
		$del = "DELETE FROM {$this->sectb} WHERE PID='{$id}' AND CID IN ('".implode("', '", $rsecs)."')";
		
		# Remove section in database
		if(!$this->mysqli->query($del)) {
			$this->notif[] = "ERROR: del proj-sec";
		}
	} # function remove
	
	/**
	* Remove files
	* Remove files in a section
	* 
	* @access public
	* @param array $secs Sections
	* @param array $rimgs Images to be removed
	* @param array $rdocs Documents to be removed
	* @param string $id ID of area
	*/
	public function removeFile($id, $secs, $rimgs, $rdocs) {
		# Run through each section
		foreach($secs["id"] as $i => $secID) {
			# Images to be removed
			if(!empty($rimgs[$i])) {
				$del = "DELETE FROM {$this->imgsectb} WHERE PID='{$id}' AND CID='{$secID}' AND ImgID IN ('".implode("', '", $rimgs[$i])."')";
				
				# Do mysql removal
				if(!$this->mysqli->query($del)) {
					$this->notif[] = "ERROR: del sec-img $secID";
				}
			}
			
			# Documents to be removed
			if(!empty($rdocs[$i])) {
				$del = "DELETE FROM {$this->docsectb} WHERE PID='{$id}' AND CID='{$secID}' AND DocID IN ('".implode("', '", $rdocs[$i])."')";
				
				# Remove in mysql db
				if(!$this->mysqli->query($del)) {
					$this->notif[] = "ERROR: del sec-doc $secID";
				}
			}
		}
	} # function removeFile
}
?>